/**
 * Created by tanbingqin on 2020/6/30.
 */
import React  from 'react'
import moment from 'moment';
import { message } from 'antd'
import { messages, uniqueArr, queryCurrencyPrecision } from 'share/common'
import travelUtil from 'containers/request/travel-request/travelUtil'

export default {
  //处理是否启用时间
  processEnableTime(field) {
    let enableTime = false;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint) && JSON.parse(field.fieldConstraint).enableTime) {
      enableTime = true;
    }
    return enableTime;
  },

  //处理启用时间默认值
  processDefaultTime(field) {
    let defaultTime = null;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint)) {
      if (JSON.parse(field.fieldConstraint).defaultTime) {
        defaultTime = moment(moment(JSON.parse(field.fieldConstraint).defaultTime).format('HH:mm'), 'HH:mm');
      } else {
        //ps 暂不支持多个启用时间的开始日期，结束日期控件
        if (field.messageKey === 'start_date' || field.messageKey === 'com_start_date') {
          defaultTime = moment('00:00', 'HH:mm');
        }
        if (field.messageKey === 'end_date' || field.messageKey === 'com_end_date') {
          defaultTime = moment('23:59', 'HH:mm');
        }
      }
    }
    return defaultTime;
  },

  /**
   * 获取行程头日期默认值
   * @param custFormValues 单据控件
   * @param headList 行程头列表
   * @param type startDate, endDate
   */
  processDefaultHeadDate(custFormValues, headList, type) {
    let startDate = null;
    let endDate = null;
    custFormValues.forEach(item => {
      if (item.messageKey === 'start_date') {
        startDate = item.value;
      }
      if (item.messageKey === 'end_date') {
        endDate = item.value;
      }
    });
    let headLength = headList.length;
    if (headLength) {
      startDate = headList[headLength - 1].endDate;
    }
    startDate = moment(moment(startDate).format('YYYY-MM-DD'));//置为零点零分
    endDate = moment(moment(endDate).format('YYYY-MM-DD'));//置为零点零分
    return type === 'startDate' ? startDate : endDate;
  },

  /**
   * 获取行程头城市默认值
   * @param headList 行程头列表
   * @param nameKey cityName的key fromCityName, toCityName
   * @param codeKey cityCode的key fromCityCode, toCityCode
   */
  processDefaultHeadCity(headList, nameKey, codeKey) {
    let result = {
      [nameKey]: '',
      [codeKey]: ''
    };
    let headLength = headList.length;
    if (headLength) {
      result[nameKey] = headList[headLength - 1][nameKey];
      result[codeKey] = headList[headLength - 1][codeKey];
    }
    return result;
  },

  disabledDate(current, custFormValues) {
    let startDate = null;
    let endDate = null;
    custFormValues.forEach(item => {
      if (item.messageKey === 'start_date') {
        startDate = item.value;
      }
      if (item.messageKey === 'end_date') {
        endDate = item.value;
      }
    });
    return moment(current).isBefore(moment(startDate), 'day') || moment(current).isAfter(moment(endDate), 'day');
  },

  disabledDateByParam(current, startDate, endDate, isCombine) {
    return isCombine ? moment(current).isBefore(moment(startDate), 'day') || moment(current).isAfter(moment(endDate), 'day') : false;
  },

  //处理批量保存行程头数据
  processHeadParams(headList) {
    let result = [];
    headList && headList.forEach(item => {
      result.push({
        itineraryHeadId: item.itineraryHeadId,
        applicationOID: item.applicationOID,
        fromCityName: item.fromCityName,
        fromCityCode: item.fromCityCode,
        toCityName: item.toCityName,
        toCityCode: item.toCityCode,
        startDate: moment(moment(item.startDate).format('YYYY-MM-DD')).utc().format(),
        endDate: moment(moment(item.endDate).format('YYYY-MM-DD')).utc().format()
      });
    });
    return result
  },

  //isAdd 是否是添加一程的校验，添加一程时需额外校验连续添加数量
  validateHead(isAdd, tempHeadList) {
    let isHasEmptyCity = false;
    let isHasErrDate = false; //结束日期是否是早于开始日期
    tempHeadList.forEach(tempHead => {
      if (!tempHead.fromCityCode || !tempHead.toCityCode) {
        isHasEmptyCity = true;
      }
      if (moment(tempHead.endDate).isBefore(moment(tempHead.startDate), 'day')) {
        isHasErrDate = true;
      }
    });
    if (isHasEmptyCity) {
      message.error(messages('request-1.key428')/*请填写城市*/);
      return false;
    }
    if (tempHeadList.length === 5 && isAdd) {
      message.error(messages('request-1.key429')/*最多连续添加5个行程*/);
      return false;
    }
    if (isHasErrDate) {
      message.error(messages('request-1.key430')/*结束日期不能早于开始日期*/);
      return false;
    }
    return true;
  },

  //是否有勾选的快捷规划
  isSelectQuick(tempHeadList) {
    let isSelect = false;
    tempHeadList && tempHeadList.forEach(tempHead => {
      if (tempHead.quickExpenseOIDList && tempHead.quickExpenseOIDList.length) {
        isSelect = true;
      }
    });
    return isSelect;
  },

  /**
   * 选中的快捷规划费用类型的并集去重
   * @param tempHeadList
   * @param expenseTypeList
   */
  getAllSelectQuick(tempHeadList, expenseTypeList) {
    let expenseType = [];
    let expenseTypeOIDList = [];
    tempHeadList && tempHeadList.forEach(tempHead => {
      if (tempHead.quickExpenseOIDList && tempHead.quickExpenseOIDList.length) {
        expenseTypeOIDList.push(...tempHead.quickExpenseOIDList);
      }
    });
    expenseTypeOIDList = uniqueArr(expenseTypeOIDList);
    expenseTypeList && expenseTypeList.forEach(expense => {
      if (expenseTypeOIDList.indexOf(expense.expenseTypeOID) > -1) {
        expenseType.push(expense);
      }
    });
    return expenseType;
  },

  getQuickExpense(expenseTypeOID, expenseTypeList) {
    let expense = {};
    expenseTypeList && expenseTypeList.forEach(expenseType => {
      if (expenseType.expenseTypeOID === expenseTypeOID) {
        expense = JSON.parse(JSON.stringify(expenseType));
      }
    });
    return expense;
  },

  /**
   * 生成一个费用下要编辑的控件字段customFormFields
   * @param itineraryHeadId
   * @param expenseTypeOID
   * @param expenseForms
   */
  getFormFields(itineraryHeadId, expenseTypeOID, expenseForms) {
    let customFormFields = [];
    let widgetMessageKey = '';
    expenseForms && expenseForms.forEach(expenseForm => {
      if (expenseForm.expenseTypeOID === expenseTypeOID) {
        customFormFields = JSON.parse(JSON.stringify(expenseForm.customFormFields));
        widgetMessageKey = expenseForm.widgetMessageKey;
      }
    });
    customFormFields.forEach(formField => {
      //给个前端识别用的id
      //这样改动原因：不同费用下的fieldOID可能一样，不同行程头下的快捷费用expenseTypeOID可以一样
      formField.frontID = `${itineraryHeadId}|${expenseTypeOID}|${formField.fieldOID}`;
      formField.widgetMessageKey = formField.guiWidgetOID ? widgetMessageKey : ''; //所属套件的messageKey
      formField.formWidgetMessageKey = widgetMessageKey; //每个控件给个这个字段，表示这个费用表单是否有配置什么套件，不能根据此字段判断是否是套件的子组件
    });
    return customFormFields || [];
  },

  /**
   * 生成一个费用下要编辑的控件字段customFormFields
   * @param itinerary 行程相关信息
   * @param expenseTypeOID
   * @param budgetId 要编辑的预算明细
   */
  getFormValues(itinerary, expenseTypeOID, budgetId) {
    let customFormFields = [];
    let widgetMessageKey = '';
    itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
      if (budget.applicationCustomBudgetId === budgetId) {
        customFormFields = JSON.parse(JSON.stringify(budget.expenseBudgetCustomValueDTOs));
        widgetMessageKey = budget.widgetMessageKey;
      }
    });
    customFormFields && customFormFields.forEach(formField => {
      //给个前端识别用的id
      //这样改动原因：不同费用下的fieldOID可能一样，不同行程头下的快捷费用expenseTypeOID可以一样
      formField.frontID = `${itinerary.itineraryHeadId}|${expenseTypeOID}|${formField.fieldOID}`;
      formField.widgetMessageKey = formField.guiWidgetOID ? widgetMessageKey : ''; //所属套件的messageKey
      formField.formWidgetMessageKey = widgetMessageKey; //每个控件给个这个字段，表示这个费用表单是否有配置什么套件，不能根据此字段判断是否是套件的子组件
    });
    return customFormFields || [];
  },

  /**
   * 返回预算费用表单的表单oid
   * @param expenseTypeOID
   * @param expenseForms
   */
  getBudgetFormOID(expenseTypeOID, expenseForms) {
    let formOID = '';
    expenseForms && expenseForms.forEach(expenseForm => {
      if (expenseForm.expenseTypeOID === expenseTypeOID) {
        formOID = expenseForm.formOID;
      }
    });
    return formOID;
  },

  getMaxLength(field) {
    let maxLength = undefined;
    switch (field.messageKey) {
      case 'com_remarks':
        maxLength = 500;
        break;
      case 'com_text_area':
        maxLength = 1000;
        break;
    }
    if (['com_remarks', 'com_text_area'].indexOf(field.messageKey) > -1 && field.fieldContent && JSON.parse(field.fieldContent).maxLength) {
      maxLength = JSON.parse(field.fieldContent).maxLength;
    }
    return maxLength;
  },

  //是否展示控件
  //formInfo单据表单信息，不是费用表单信息
  isShowField(field, formInfo) {
    let isShow = true;
    //配置了隐藏，则不展示控件
    if (field.hide) {
      isShow = false;
    }
    //套件下的城市控件不展示
    if ((field.messageKey === 'com_departure_city' || field.messageKey === 'com_arrival_city' || field.messageKey === 'com_city') && field.widgetMessageKey) {
      isShow = false;
    }
    //机票套件下的日期连选不展示
    if (field.widgetMessageKey === 'suite_flight' && field.messageKey === 'com_range_picker') {
      isShow = false;
    }

    //火车套件下的日期不展示
    if (field.widgetMessageKey === 'suite_train' && field.messageKey === 'com_date') {
      isShow = false;
    }

    //用餐,酒店套件下的日期连选是否展示
    let propertyMap = formInfo.customFormPropertyMap;
    if (['suite_dining', 'suite_hotel'].indexOf(field.widgetMessageKey) > -1 && field.messageKey === 'com_range_picker') {
      if (propertyMap['application.date.allow.change']) {
        let propertyValue = JSON.parse(propertyMap['application.date.allow.change']) || {};
        if (propertyValue.dateAllowChange && (
          (field.widgetMessageKey === 'suite_dining' && propertyValue.types.indexOf('dining') > -1) ||
          (field.widgetMessageKey === 'suite_hotel' && propertyValue.types.indexOf('hotel') > -1)
        )) {
          isShow = true;
        } else {
          isShow = false;
        }
      } else {
        isShow = false;
      }
    }
    return isShow;
  },

  //是否展示预算刷新按钮
  //formInfo单据表单信息，不是费用表单信息
  isShowBudgetRefresh(field, formInfo) {
    let isShow = false;
    let propertyMap = formInfo.customFormPropertyMap;
    //裂开来，套件下的子组件才塞了widgetMessageKey，预算控件不是套件下的，所以要从费用表单上widgetMessageKey来判断套件类型
    if (propertyMap['itinerary.auto.budget2'] && field.formWidgetMessageKey) {
      let propertyValue = JSON.parse(propertyMap['itinerary.auto.budget2']) || {};
      if (propertyValue.enabled
        && propertyValue.itineraryTypes.indexOf(field.formWidgetMessageKey.split('_')[1]) > -1
        && ['flight', 'train', 'hotel'].indexOf(field.formWidgetMessageKey.split('_')[1]) > -1) {
        isShow = true;
      }
    }
    return isShow;
  },

  /**
   * 获取分摊上要使用的单据companyOID和departmentOID
   * @param customValues 单据控件列表
   * @param jobInfo 岗位信息
   * @param company 申请人所在公司
   * @param type 'company', 'department'
   */
  getApportionCompanyDepartment(customValues, jobInfo, company, type) {
    let resultOID = '';
    if (type === 'company') {
      resultOID = (jobInfo && jobInfo.companyOID) || company.companyOID;
    }
    if (type === 'department') {
      resultOID = jobInfo && jobInfo.departmentOID;
    }
    let messageKey = type === 'company' ? 'select_company' : 'select_department';
    customValues && customValues.forEach(customValue => {
      if (customValue.messageKey === messageKey && customValue.value) {
        resultOID = customValue.value;
      }
    });
    return resultOID;
  },

  //初始化分摊模板
  initApportionTemplate(customValues, apportionTemplate) {
    let isHasDepartment = false; //表单是否配置了部门控件
    //先清空模板数据
    apportionTemplate.costCenterItems = [];
    let departmentCostCenterItem = {};
    customValues.map(customValue => {
      let costCenterItem = {};
      //处理部门
      if (customValue.messageKey === 'select_department') {
        isHasDepartment = true;
        costCenterItem.type = 1;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenter = '00000000-0000-0000-0000-000000000000';
        costCenterItem.costCenterOID = '';    //部门oid
        departmentCostCenterItem = JSON.parse(JSON.stringify(costCenterItem));
      }
      //处理成本中心
      if (customValue.messageKey === 'select_cost_center') {
        costCenterItem.type = 0;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenterOID = '';    //成本中心项oid
        costCenterItem.required = customValue.required;
        //配置了参与分摊的才塞入分摊项中
        if (customValue.dataSource && costCenterItem.isApportionItem) {
          let tmp = JSON.parse(customValue.dataSource);
          //配得有问题的成本中心不塞入费用分摊中
          if (tmp.type) {
            costCenterItem.costCenterType = tmp.type;
          }
          costCenterItem.costCenter = tmp.costCenterOID;
          apportionTemplate.costCenterItems.push(costCenterItem);
        }
      }
    });
    //如果没有配置部门也要塞入一个部门控件
    if (!isHasDepartment) {
      departmentCostCenterItem = {
        type: 1,
        fieldName: messages('common.department')/*部门*/,
        isApportionItem: true,
        name: '',
        costCenter: '00000000-0000-0000-0000-000000000000',
        costCenterOID: ''
      };
    }
    if (departmentCostCenterItem.isApportionItem) {
      apportionTemplate.costCenterItems.splice(0, 0, departmentCostCenterItem);//部门放在第一个
    }
  },

  //初始化默认分摊
  initDefaultApportion(customValues, newProfile, jobInfo) {
    let defaultApportion = {
      entityType: 1001,
      scale: 100,
      amount: 0,
      defaultApportion : true,
      costCenterItems: []
    };
    let isHasDepartment = false; //表单是否配置了部门控件
    let parentCostCenterOID = '';//父成本中心项oid
    let departmentCostCenterItem = {};
    customValues && customValues.forEach(customValue => {
      let costCenterItem = {};
      //处理部门
      if (customValue.messageKey === 'select_department') {
        isHasDepartment = true;
        costCenterItem.type = 1;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenterOID = '';
        costCenterItem.costCenter = '00000000-0000-0000-0000-000000000000';
        if (customValue.showValue) {
          costCenterItem.name = customValue.showValue;
          costCenterItem.pathDepth = 1;
          costCenterItem.costCenterOID = customValue.value;//部门oid
        }
        departmentCostCenterItem = JSON.parse(JSON.stringify(costCenterItem));
      }
      //处理成本中心
      if (customValue.messageKey === 'select_cost_center') {
        costCenterItem.type = 0;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenterOID = '';    //成本中心项oid
        costCenterItem.required = customValue.required;
        //配置了参与分摊的才塞入分摊项中
        if (customValue.dataSource && costCenterItem.isApportionItem) {
          let tmp = JSON.parse(customValue.dataSource);
          //配得有问题的成本中心不塞入费用分摊中
          if (tmp.type) {
            costCenterItem.costCenterType = tmp.type;
            if (tmp.type === 'father' && customValue.value) {
              parentCostCenterOID = customValue.value;
            }
            //子成本中心在父成本中心之后，此时parentCostCenterOID已赋值
            if (tmp.type === 'son' && parentCostCenterOID) {
              costCenterItem.parentCostCenterOID = parentCostCenterOID;
            }
          }
          costCenterItem.costCenter = tmp.costCenterOID;
          costCenterItem.costCenterOID = customValue.value ? customValue.value : '';
          costCenterItem.name = customValue.showValue;
          defaultApportion.costCenterItems.push(costCenterItem);
        }
      }
    });
    //如果没有配置部门也要塞入一个部门控件
    if (!isHasDepartment) {
      let departName = '';
      let pathDepth = 1;
      if (newProfile && newProfile['department'] && newProfile['department']['fullPathDisabled'] === 'true' && jobInfo.departmentName) {
        let array = jobInfo.departmentName.split('|');
        departName = array[array.length - 1];
        pathDepth = array.length;
      } else {
        departName = jobInfo.departmentName;
      }
      departmentCostCenterItem = {
        type: 1,
        fieldName: messages('common.department')/*部门*/,
        isApportionItem: true,
        name: departName,
        pathDepth: pathDepth,
        costCenter: '00000000-0000-0000-0000-000000000000',
        costCenterOID: jobInfo.departmentOID
      };
    }
    if (departmentCostCenterItem.isApportionItem) {
      defaultApportion.costCenterItems.splice(0, 0, departmentCostCenterItem);//部门放在第一个
    }
    return defaultApportion;
  },

  validateApportion(apportionList) {
    let i = 0;
    for (i; i < apportionList.length; i++) {
      //判断分摊金额和分摊比例是否大于0
      if (!apportionList[i].amount || !apportionList[i].scale) {
        message.error(messages('request-1.key320')/*分摊金额和比例必须大于0*/);
        return false;
      }
      //判断分摊项是否有填, 校验部门必填，成本中心是否必填根据required字段判断
      //判断分摊项是否有填时加一层校验，只在参与分摊的项中校验是否有填 这层校验可以去了，只有参与分摊的才会被塞入分摊项中
      //如果分摊项都没有参与分摊，也要报错提示
      let j = 0;
      let isEmptyApportionItem;
      for(j; j < apportionList[i].costCenterItems.length; j++) {
        if (!apportionList[i].costCenterItems[j].costCenterOID
          && apportionList[i].costCenterItems[j].type === 1) {
          message.error(messages('request-1.key237')/*有未填写的分摊项*/);
          return false;
        }
        if (!apportionList[i].costCenterItems[j].costCenterOID
          && apportionList[i].costCenterItems[j].type === 0
          && apportionList[i].costCenterItems[j].required) {
          message.error(messages('request-1.key237')/*有未填写的分摊项*/);
          return false;
        }
        if (!apportionList[i].costCenterItems.length) {
          isEmptyApportionItem = true;
        }
      }
      if (isEmptyApportionItem) {
        message.error(messages('request-1.key238')/*费用分摊中的明细信息不完整，请完善*/);
        return false;
      }
    }
    return true;
  },

  validateBudgetAmount(customValues, currencyCode, amount, expenseTypeName) {
    let isHasBudget = false;
    let isRequired = false;
    let fieldName = '';
    customValues && customValues.forEach(item => {
      if (item.messageKey === 'com_budget') {
        isHasBudget = true;
        isRequired = item.required;
        fieldName = item.fieldName;
      }
    });
    if (isHasBudget) {
      let isNumber = false;
      let number = amount;
      number = number + '';
      number = number.trim();
      isNumber = !isNaN(number) && number !== '';
      if (isRequired || isNumber || currencyCode) {
        if (!isNumber || !currencyCode) {
          message.error(messages('request-1.key431',{arg1: expenseTypeName,arg2: fieldName})/*请填写{arg1}的{arg2}*/);
          return false;
        }
      }
      if (!isNumber || (isNumber && Number(number) <= 0)) {
        message.error(messages('request-1.key854')/*预算金额必须大于0*/);
        return false;
      }
    }
    return true;
  },

  validateHotelDate(customValues) {
    let startDate = '';
    let endDate = '';
    customValues && customValues.forEach(item => {
      if (item.messageKey === 'com_start_date' && item.widgetMessageKey === 'suite_hotel') {
        startDate = item.value;
      }
      if (item.messageKey === 'com_end_date' && item.widgetMessageKey === 'suite_hotel') {
        endDate = item.value;
      }
    });
    if (startDate && endDate && moment(startDate).isSame(endDate, 'day')) {
      message.error(messages('request-1.key855')/*开始结束日期为同一天时，不允许添加酒店*/);
      return false;
    }
    return true;
  },

  //获取明细列表展示币种 金额的信息，如果没有配置com_budget，则不展示，又改了，现在是金额不大于0就不展示
  //差补明细金额逻辑额外处理
  getAmountStr(customValues, itineraryBudget) {
    let result = '';
    let amount = 0;
    customValues && customValues.forEach(item => {
      if (item.messageKey === 'com_budget') {
        let value = item.value ? JSON.parse(item.value) : {};
        result += value.currencyCode ? `${value.currencyCode} ` : '';
        result += React.Component.prototype.filterMoney(value.amount, queryCurrencyPrecision(value.currencyCode), true);
        amount = value.amount || 0;
      }
    });
    if (itineraryBudget.itineraryType === 1006) {
      result += itineraryBudget.currencyCode ? `${itineraryBudget.currencyCode} ` : '';
      result += React.Component.prototype.filterMoney(itineraryBudget.amount, queryCurrencyPrecision(itineraryBudget.currencyCode), true);
      amount = itineraryBudget.amount || 0;
    }
    if (amount === 0) {
      result = '';
    }
    return result;
  },

  renderAmountStr(currencyCode, amount) {
    let result = '';
    result += currencyCode ? `${currencyCode} ` : '';
    result += React.Component.prototype.filterMoney(amount, queryCurrencyPrecision(currencyCode), true);
    return result;
  },

  //获取公司支付展示文案 配置了公司支付控件，且值为true
  getCompanyPaidStr(customValues) {
    let result = '';
    customValues && customValues.forEach(item => {
      if (item.messageKey === 'com_company_paid' && item.showValue === 'true') {
        result = messages('request-1.key293')/*公司支付*/;
      }
    });
    return result;
  },

  /**
   * 校验改变后的日期是否包含行程日期范围
   * @param startDate
   * @param endDate
   * @param headList 行程头列表
   */
  judgeItineraryDateRange(startDate, endDate, headList) {
    let result = true; //校验结果 true表示校验通过
    let start = startDate;
    let end = endDate;
    //不管是否启用时间，都按零点时间计算
    start = moment(start).hours(0).minutes(0).seconds(0).utc().format();
    end = moment(end).hours(23).minutes(59).seconds(59).utc().format();
    headList && headList.forEach(itinerary => {
      if (!this.judgeSubset(start, end, itinerary.startDate) || !this.judgeSubset(start, end, itinerary.endDate)) {
        result = false;
      }
    });
    return result;
  },

  //校验日期date是否在start，end之间，包含两侧日期，精度到秒
  judgeSubset(start, end, date) {
    return moment(date).isSame(start) || moment(date).isSame(end) || moment(date).isBetween(start, end, 'second');
  },

  //是否弹统一订票弹框
  isShowModal(itineraryHeadList, customFormPropertyMap) {
    let flight = false;//是否显示飞机统一订票
    let flightPlatform = false; //是否有支持订票平台的机票行程
    let train = false;//。。。。火车统一订票
    let hotel = false;//是否显示酒店统一订票
    let dining = false; //是否显示用餐统一订票
    let didi = false; //是否显示用车统一订票 用车只有各自订票
    itineraryHeadList && itineraryHeadList.forEach(itineray => {
      itineray.itineraryBudgetDTOList && itineray.itineraryBudgetDTOList.forEach(budget => {
        let valueEntity = {}; //消费商相关配置
        if (['suite_flight', 'suite_train', 'suite_hotel'].indexOf(budget.widgetMessageKey) > -1) {
          budget.expenseBudgetCustomValueDTOs && budget.expenseBudgetCustomValueDTOs.forEach(item => {
            if (item.messageKey === 'com_prosumer') {
              valueEntity = item.valueEntity ? JSON.parse(item.valueEntity) : {};
            }
          });
        }
        if (budget.widgetMessageKey === 'suite_flight') {
          //设置是否有支持订票平台的机票行程
          if (valueEntity.supplierPlatFormEnable) {
            flightPlatform = true;
          }
          //设置是否有非支持订票平台的机票行程
          if (!valueEntity.supplierPlatFormEnable && valueEntity.supplierConfig && JSON.parse(valueEntity.supplierConfig)
            && JSON.parse(valueEntity.supplierConfig)[0].pushType !== 'NEVER') {
            flight = true;
          }
        }
        if (budget.widgetMessageKey === 'suite_train') {
          if (valueEntity.supplierConfig && JSON.parse(valueEntity.supplierConfig) && JSON.parse(valueEntity.supplierConfig)[0].pushType !== 'NEVER') {
            train = true;
          }
        }
        if (budget.widgetMessageKey === 'suite_hotel') {
          if (valueEntity.supplierConfig && JSON.parse(valueEntity.supplierConfig) && JSON.parse(valueEntity.supplierConfig)[0].pushType !== 'NEVER') {
            hotel = true;
          }
        }
        if (budget.widgetMessageKey === 'suite_dining') {
          dining = true;
        }
      });
    });
    //处理机票，火车，用餐固定各自订票隐藏逻辑
    if (customFormPropertyMap) {
      let maps = customFormPropertyMap;
      if (travelUtil.processUniformFixed('ca.travel.bookingpreference', maps)) {
        flight = false;
      }
      if (travelUtil.processUniformFixed('ca.travel.train.bookingpreference', maps)) {
        train = false;
      }
      if (travelUtil.processUniformFixed('ca.travel.dining.bookingpreference', maps)) {
        dining = false;
      }
    }
    return { flight, flightPlatform, train, hotel, dining };
  },

  //统一订票人去重
  processUniformBooking(bookerList) {
    let buffBookerList = [];
    bookerList.forEach(booker => {
      let isExist = false;
      buffBookerList.forEach(buffBooker => {
        if (booker.oid === buffBooker.oid) {
          isExist = true;
        }
      });
      if (!isExist) {
        buffBookerList.push(booker);
      }
    });
    return buffBookerList;
  },

  //提交时加签人校验
  judgeSubmitSign(params) {
    let duplicateNameList = [];
    let duplicateOIDList = [];//去重逻辑
    let duplicateName = '';
    if (params.countersignApproverOIDs && params.countersignApproverOIDs.length && params.approvalHistorys && params.approvalHistorys.length) {
      params.approvalHistorys.map(history =>{
        if (history.operation === 2001 && history.operator
          && params.countersignApproverOIDs.indexOf(history.operator.userOID) !== -1
          && history.operator.fullName && duplicateOIDList.indexOf(history.operator.userOID) === -1) {
          duplicateNameList.push(history.operator.fullName);
          duplicateOIDList.push(history.operator.userOID);
        }
      });
    }
    duplicateName = duplicateNameList.join(', ');
    return duplicateName;
  },

  //判断是否显示底部审批／驳回等按钮
  showApproveButton(approvalChain, approvalChains, currentUserId, status) {
    let showBottom = false;
    if(status!==1002){
      return;
    }
    if(approvalChain){
      if(approvalChain.approverOID == currentUserId && approvalChain.nodeType === 1001){
        showBottom = true;
      }
    }
    if(approvalChains){
      approvalChains.forEach((approver) => {
        if(approver.approverOID == currentUserId && approver.nodeType === 1001){
          showBottom = true;
        }else{
          if(approver.proxyApproverOIDs){
            approver.proxyApproverOIDs.forEach((proxyApprover) => {
              if(proxyApprover == currentUserId && approver.nodeType === 1001){
                showBottom = true;
              }
            })
          }
        }
      })
    }
    return showBottom;
  },

  /**
   * 获取统一订票展示文案
   * @param budget 行程明细
   * @param info 申请单详情
   */
  getUniformStr(budget, info) {
    let str = '';
    if (['suite_flight', 'suite_train', 'suite_hotel', 'suite_dining'].indexOf(budget.widgetMessageKey) > -1) {
      switch (budget.widgetMessageKey) {
        case 'suite_flight':
          let valueEntity = {}; //消费商相关配置
          budget.expenseBudgetCustomValueDTOs && budget.expenseBudgetCustomValueDTOs.forEach(item => {
            if (item.messageKey === 'com_prosumer') {
              valueEntity = item.valueEntity ? JSON.parse(item.valueEntity) : {};
            }
          });
          if (valueEntity.supplierPlatFormEnable && info.travelApplication && info.travelApplication.platformBookingClerkName) {
            str = messages('request-1.key432',{arg1: info.travelApplication.platformBookingClerkName})/*订票平台机票由{arg1}统一订票*/;
          }
          if (!valueEntity.supplierPlatFormEnable && info.travelApplication && info.travelApplication.uniformBooking
            && info.travelApplication.bookingClerkName ) {
            str = messages('request-1.key433',{arg1: info.travelApplication.bookingClerkName})/*由 {arg1} 统一订机票*/;
          }
          break;
        case 'suite_train':
          if (info.travelApplication && info.travelApplication.trainUniformBooking && info.travelApplication.trainBookingClerkName) {
            str = messages('request-1.key434',{arg1: info.travelApplication.trainBookingClerkName})/*由 {arg1} 统一订火车票*/;
          }
          break;
        case 'suite_hotel':
          if (info.travelApplication && info.travelApplication.hotelUniformBooking && info.travelApplication.hotelBookingClerkName) {
            str = messages('request-1.key435',{arg1: info.travelApplication.hotelBookingClerkName})/*由 {arg1} 统一订酒店*/;
          }
          break;
        case 'suite_dining':
          if (info.travelApplication && info.travelApplication.diningUniformBooking && info.travelApplication.diningBookingClerkName) {
            str = messages('request-1.key436',{arg1: info.travelApplication.diningBookingClerkName})/*由 {arg1} 统一订餐*/;
          }
          break;
      }
    }
    return str;
  },

  /**
   * 是否有订单数据,并返回travel-order-list组件需要的数据
   * 兼容预订按钮控件所需要的数据
   * @param budget 行程明细
   */
  isHasOrder(budget) {
    let isHas = false;
    let type = '';
    let orderList = [];
    let orderItinerary = {
      itineraryDirection: 1001, //行程卡片只有单程
      supplierOID: budget.supplierOID,
      supplierConfig: budget.supplierConfig,
      approvalNumber: budget.approvalNumber,
      approvalNum: budget.approvalNumber, //兼容老数据的字段名
      bookedStatus: budget.bookedStatus,
      supplierServiceName: budget.supplierServiceName
    };
    if (budget.widgetMessageKey) {
      type = budget.widgetMessageKey.split('_').length > 1 ? budget.widgetMessageKey.split('_')[1] : '';
    }
    if (budget.widgetMessageKey === 'suite_flight' && budget.flightOrderDetails && budget.flightOrderDetails.length) {
      isHas = true;
      orderList = budget.flightOrderDetails;
    }
    if (budget.widgetMessageKey === 'suite_train' && budget.trainOrderInfoList && budget.trainOrderInfoList.length) {
      isHas = true;
      orderList = budget.trainOrderInfoList;
    }
    if (budget.widgetMessageKey === 'suite_hotel' && budget.travelHotelOrderInfoDTOs && budget.travelHotelOrderInfoDTOs.length) {
      isHas = true;
      orderList = budget.travelHotelOrderInfoDTOs;
    }
    return {
      isHas,
      type,
      orderList,
      orderItinerary
    };
  },

  //差补配置里是否配置了行程值列表
  isHasCustList(config) {
    let isHas = false;
    config && config.itineraryHeadPropertyDTOs && config.itineraryHeadPropertyDTOs.forEach(itinerary => {
      if (itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs
        && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs.length) {
        isHas = true;
      }
    });
    return isHas;
  },

  //校验影响差补类型获取的参数字段，如果是必填的话，是否都已有值
  judgeIsAllHaveValue(subsidyConfig, itineraryIndex) {
    let isAll = true;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    let custList = itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs;
    custList && custList.forEach(cust => {
      if (!cust.value) {
        isAll = false;
      }
    });
    return isAll;
  },

  isSelectAll(itinerary) {
    let isAll = false;
    if (itinerary.expenseTypeOIDs && itinerary.expenseTypes && itinerary.expenseTypeOIDs.length === itinerary.expenseTypes.length) {
      isAll = true;
    }
    return isAll;
  },

  /**
   * 判断一个预算明细是否是差补预算明细
   * @param itinerary 行程相关信息
   * @param budgetId 要编辑的预算明细
   */
  isSubsidy(itinerary, budgetId) {
    let customFormFields = [];
    let widgetMessageKey = '';
    let isSubsidy = false;
    itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
      if (budget.applicationCustomBudgetId === budgetId && budget.itineraryType === 1006) {
        isSubsidy = true;
      }
    });
    return isSubsidy;
  },

  /**
   * 判断是否有差补预算明细
   * @param itineraryList 行程列表相关信息
   */
  isHasSubsidy(itineraryList) {
    let isHasSubsidy = false;
    itineraryList && itineraryList.forEach(itinerary => {
      itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
        if (budget.itineraryType === 1006) {
          isHasSubsidy = true;
        }
      });
    });
    return isHasSubsidy;
  },

  /**
   * 判断是否有预算明细
   * @param itineraryList 行程列表相关信息
   */
  isHasBudgetDetail(itineraryList) {
    let isHasBudgetDetail = false;
    itineraryList && itineraryList.forEach(itinerary => {
      if (itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.length) {
        isHasBudgetDetail = true;
      }
    });
    return isHasBudgetDetail;
  },

  /**
   * 抽出差补明细行
   * @param itinerary 行程相关信息
   * @param budgetId 要编辑的预算明细
   */
  getSubsidyInfo(itinerary, budgetId) {
    let subsidyInfo = {};
    itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
      if (budget.applicationCustomBudgetId === budgetId && budget.itineraryType === 1006) {
        subsidyInfo = JSON.parse(JSON.stringify(budget));
      }
    });
    return subsidyInfo;
  },

  /**
   * 行程卡片申请单是否展示去借款按钮
   * @param info 单据详情
   * @param customFormPropertyMap 表单属性配置
   */
  isShowAutoLoanBtn(info, customFormPropertyMap) {
    let isShow = false;
    if (info.formType === 2001
      && customFormPropertyMap["application.funds"] === "true"
      && customFormPropertyMap["application.direct.loan.enabled"] === "true"
      && customFormPropertyMap["application.direct.loan.type"]) {
      isShow = true;
    }
    //如果已开启了额度，则不能去借款
    //如果已有去借款数据，也不展示按钮，只展示单据跳转链接
    if (info.takeQuota || info.loanBillOID) {
      isShow = false;
    }
    return isShow;
  },

  /**
   * 行程卡片申请单是否展示申请额度按钮
   * @param info 单据详情
   * @param customFormPropertyMap 表单属性配置
   */
  isShowLimitLoanBtn(info, customFormPropertyMap) {
    let isShow = false;
    if (info.formType === 2001
      && customFormPropertyMap["application.funds"] === "true"
      && customFormPropertyMap["application.direct.loan.enabled"] === "false") {
      isShow = true;
    }
    //和去借款功能互斥
    if (info.loanBillOID) {
      isShow = false;
    }
    //如果已经开启了申请额度，则不用管配置也要展示
    if (!isShow && info.takeQuota) {
      isShow = true;
    }
    return isShow;
  },

  //校验两个行程头是否一致
  isChangeHead(oldHead, newHead) {
    let isChange = false;
    //isEdit 贬价状态，可保证newHead里数据有值
    if (newHead.isEdit) {
      if (newHead.fromCityCode !== oldHead.fromCityCode || newHead.toCityCode !== oldHead.toCityCode) {
        isChange = true;
      }
      if (!moment(newHead.startDate).isSame(oldHead.startDate, 'day') || !moment(newHead.endDate).isSame(oldHead.endDate, 'day')) {
        isChange = true;
      }
    }
    return isChange;
  },

  //公司控件设置禁用
  disableCompany(application) {
    let custFormValues = application.custFormValues || [];
    custFormValues.forEach(item => {
      if (item.messageKey === 'select_company') {
        item.isReadOnly = true;
      }
    });
  },

  //公司控件是否设置了默认值
  isDefaultCompany(fields) {
    let isDefault = '';
    fields && fields.forEach(item => {
      if (item.messageKey === 'select_company' && !JSON.parse(item.fieldConstraint || '{}').noDefault) {
        isDefault = item.fieldOID;
      }
    });
    return isDefault;
  },
}
